import { HttpContext } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators, UntypedFormGroup, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { I18nPipe, _HttpClient } from '@delon/theme';
import { NzAlertModule } from 'ng-zorro-antd/alert';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzImageModule } from 'ng-zorro-antd/image';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'passport-forgot',
  templateUrl: './forgot.component.html',
  styleUrls: ['./forgot.component.less'],
  changeDetection: ChangeDetectionStrategy.Default,
  imports: [NzAlertModule, ReactiveFormsModule, NzFormModule, NzInputModule, NzImageModule, NzButtonModule, I18nPipe]
})
export class ForgotComponent implements OnInit {
  captcha: NzSafeAny = {};
  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);
  private readonly fb = inject(UntypedFormBuilder);
  private readonly router = inject(Router);

  constructor() {
    this.form = this.fb.group({
      email: [null, [Validators.required, Validators.email]],
      code: [null, [Validators.required]]
    });
  }
  get code() {
    return this.form.controls['code'];
  }
  get email() {
    return this.form.controls['email'];
  }
  form: UntypedFormGroup;
  error = '';

  count = 0;
  interval$: NzSafeAny;

  ngOnInit(): void {
    this.getCaptch();
  }

  getCaptch() {
    this.http
      .get(Api.ForgotKaptchaApi, null, {
        context: new HttpContext().set(ALLOW_ANONYMOUS, true)
      })
      .subscribe(res => {
        if (res.code == ResponseCode.SUCCESS) {
          this.captcha = res.data;
        }
      });
  }

  submit(): void {
    this.error = '';
    Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      this.form.controls[key].updateValueAndValidity();
    });
    if (this.form.invalid) {
      return;
    }
    const data = this.form.value;
    this.http
      .post(
        `${Api.ForgotPasswordApi}?code=${data.code}&email=${data.email}`,
        {},
        {},
        {
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        }
      )
      .subscribe({
        next: res => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.router.navigate(['/passport/reset'], { queryParams: { email: data.email } });
            } else {
              this.getCaptch();
              this.error = res.data;
            }
          } else {
            this.getCaptch();
            this.error = '找回失败，未知原因！';
          }
        },
        error: error => {
          console.log(error);
          this.msg.error('找回失败');
        }
      });
  }
}
